<script setup>
import { ref, computed,onMounted } from 'vue'
import { userManager } from '@/utils/user'
import { userServie } from '@/services/user_service'
import { ElMessage } from 'element-plus'


onMounted(() => {
  initUserData()
})
// 公共数据
const profileImage = ref(userManager.getUserImage() || 'https://via.placeholder.com/150')
const username = ref(userManager.getUserName() || '')
const email = ref(userManager.getUserEmail() || '')
const birthDate = ref(userManager.getBirthDate() || '1990-01-01')
const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const showPasswordForm = ref(false)
const isUploading = ref(false)
const imageFile = ref(null)

// 学生专属数据
const preferences = ref(userManager.getPreferences() || [])
const newPreference = ref('')

// 教师专属数据
const major = ref(userManager.isTeacher() ? userManager.getTeacher()?.major || '' : '')

// 计算属性判断用户类型
const isStudent = computed(() => userManager.isStudent())
const isTeacher = computed(() => userManager.isTeacher())

// 公共方法
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    isUploading.value = true
    imageFile.value = file
    const reader = new FileReader()
    reader.onload = (e) => {
      profileImage.value = e.target.result
      isUploading.value = false
    }
    reader.readAsDataURL(file)
  }
}
const initUserData = () => {
  const user = userManager.getUserInfo()
  if (!user) return
  
  username.value = user.username || ''
  email.value = user.email || ''
  profileImage.value = userManager.getUserImage() || 'https://via.placeholder.com/150'
  birthDate.value = userManager.getBirthDate() || '1990-01-01'
  
  if (userManager.isStudent()) {
    preferences.value = userManager.getPreferences()
  } else if (userManager.isTeacher()) {
    major.value = userManager.getMajor()
  }
}

const updateProfile = async () => {
  try {
    const formData = new FormData()
    formData.append('username', username.value)
    formData.append('email', email.value)
    formData.append('birthDate', birthDate.value)

    // 添加角色特定字段
    if (isStudent.value) {
      formData.append('hobbies', preferences.value.length > 0 ? preferences.value.join(',') : '')
    } else if (isTeacher.value) {
      formData.append('major', major.value)
    }

    if (imageFile.value) {
      formData.append('image', imageFile.value)
    }
     userServie.updateUserInfo(formData,(res)=>{
      userManager.setUserInfo(
      res.data.user,
      isStudent.value ? res.data.student : null,
      isTeacher.value ? res.data.teacher : null
    )
    ElMessage.success('更新成功')
    })
    
    
    
   
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 学生专属方法
const addPreference = () => {
  if (newPreference.value.trim() && !preferences.value.includes(newPreference.value.trim())) {
    preferences.value.push(newPreference.value.trim())
    newPreference.value = ''
  }
}

const removePreference = (index) => {
  preferences.value.splice(index, 1)
}

// 密码修改方法
const updatePassword = async () => {
  if (newPassword.value !== confirmPassword.value) {
    alert('两次输入的新密码不一致！')
    return
  }
  
  if (newPassword.value.length < 8 || !/\d/.test(newPassword.value) || !/[a-zA-Z]/.test(newPassword.value)) {
    alert('密码必须至少8位，包含字母和数字')
    return
  }

  try {
    await userServie.updatePassword({
      currentPassword: currentPassword.value,
      newPassword: newPassword.value
    })
    alert('密码更新成功！')
    showPasswordForm.value = false
    currentPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
  } catch (error) {
    console.error('密码更新失败:', error)
    alert('密码更新失败: ' + (error.message || '请检查当前密码是否正确'))
  }
}
</script>

<template>
  <div class="account-management">
    <div class="header">
      <h1>
        <i :class="isStudent ? 'fas fa-user-graduate' : 'fas fa-chalkboard-teacher'"></i>
        {{ isStudent ? '学生' : '教师' }}账号管理
      </h1>
      <p>管理您的账号信息和安全设置</p>
    </div>

    <div class="account-content">
      <!-- 个人信息部分 -->
      <div class="profile-section">
        <div class="section-header">
          <h2><i class="fas fa-user"></i> 个人信息</h2>
        </div>
        
        <div class="profile-form">
          <div class="avatar-upload">
            <div class="avatar-preview">
              <img :src="profileImage" alt="用户头像">
              <div class="upload-overlay" :class="{ 'uploading': isUploading }">
                <i class="fas fa-camera"></i>
                <span v-if="isUploading">上传中...</span>
              </div>
              <input 
                type="file" 
                accept="image/*"
                @change="handleImageUpload" 
                class="file-input"
              >
            </div>
            <p class="upload-hint">点击头像更换照片</p>
          </div>
          
          <div class="form-group">
            <label for="username"><i class="fas fa-signature"></i> 用户名</label>
            <input type="text" id="username" v-model="username">
          </div>
          
          <div class="form-group">
            <label for="email"><i class="fas fa-envelope"></i> 电子邮箱</label>
            <input type="email" id="email" v-model="email">
          </div>
          
          <div class="form-group">
            <label for="birthDate"><i class="fas fa-birthday-cake"></i> 出生日期</label>
            <input type="date" id="birthDate" v-model="birthDate">
          </div>
          
          <!-- 学生专属字段 -->
          <div class="form-group" v-if="userManager.isStudent()">
    <label><i class="fas fa-heart"></i> 个人喜好</label>
    <div class="preferences-container">
      <div class="preference-tag" v-for="(preference, index) in preferences" :key="index">
        {{ preference }}
        <button @click="removePreference(index)" class="remove-tag">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <div class="add-preference">
        <input 
          type="text" 
          v-model="newPreference" 
          placeholder="添加喜好" 
          @keyup.enter="addPreference"
        >
        <button @click="addPreference" class="add-btn">
          <i class="fas fa-plus"></i>
        </button>
      </div>
    </div>
  </div>
          
          <!-- 教师专属字段 -->
          <div class="form-group" v-if="userManager.isTeacher()">
    <label><i class="fas fa-graduation-cap"></i> 专业领域</label>
    <input type="text" v-model="major" placeholder="请输入您的专业">
  </div>
          
          <button class="save-btn" @click="updateProfile">
            <i class="fas fa-save"></i> 保存个人信息
          </button>
        </div>
      </div>

      <!-- 安全设置部分（共用） -->
      <div class="security-section">
        <div class="section-header">
          <h2><i class="fas fa-shield-alt"></i> 安全设置</h2>
        </div>
        
        <div class="security-content">
          <div class="password-info" v-if="!showPasswordForm">
            <p><i class="fas fa-lock"></i> 密码</p>
            <p>********</p>
            <button class="change-btn" @click="showPasswordForm = true">
              <i class="fas fa-edit"></i> 修改密码
            </button>
          </div>
          
          <div class="password-form" v-if="showPasswordForm">
            <!-- 密码表单内容保持不变 -->
             <div class="form-group">
              <label for="currentPassword"><i class="fas fa-key"></i> 当前密码</label>
              <input 
                type="password" 
                id="currentPassword" 
                v-model="currentPassword" 
                placeholder="请输入当前密码"
              >
            </div>
            
            <div class="form-group">
              <label for="newPassword"><i class="fas fa-key"></i> 新密码</label>
              <input 
                type="password" 
                id="newPassword" 
                v-model="newPassword" 
                placeholder="请输入新密码"
              >
              <p class="hint">密码长度至少8位，包含字母和数字</p>
            </div>
            
            <div class="form-group">
              <label for="confirmPassword"><i class="fas fa-key"></i> 确认新密码</label>
              <input 
                type="password" 
                id="confirmPassword" 
                v-model="confirmPassword" 
                placeholder="请再次输入新密码"
              >
            </div>
            
            <div class="form-actions">
              <button class="cancel-btn" @click="showPasswordForm = false">
                <i class="fas fa-times"></i> 取消
              </button>
              <button class="save-btn" @click="updatePassword">
                <i class="fas fa-save"></i> 保存密码
              </button>
            </div>
          </div>
          </div>
       
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 样式部分保持不变，与之前相同 */
.account-management {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  color: #333;
}

.header {
  margin-bottom: 30px;
  text-align: center;
}

.header h1 {
  font-size: 28px;
  color: #1e293b;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header h1 i {
  margin-right: 10px;
  color: #409EFF;
}

.header p {
  color: #64748b;
  font-size: 16px;
}

.account-content {
  display: grid;
  gap: 30px;
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.section-header h2 {
  font-size: 20px;
  color: #1e293b;
  display: flex;
  align-items: center;
}

.section-header h2 i {
  margin-right: 10px;
  color: #409EFF;
}

.profile-section, .security-section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  border: 1px solid #ffedd5;
}

.profile-form {
  display: grid;
  gap: 20px;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-preview {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  margin-bottom: 10px;
  border: 4px solid #ffedd5;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(3, 189, 241, 0.7);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-overlay.uploading {
  opacity: 1;
}

.avatar-preview:hover .upload-overlay:not(.uploading) {
  opacity: 1;
}

.upload-overlay i {
  font-size: 24px;
  margin-bottom: 5px;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-hint {
  color: #64748b;
  font-size: 14px;
  margin: 0;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #1e293b;
  display: flex;
  align-items: center;
}

.form-group label i {
  margin-right: 8px;
  color: #409EFF;
}

.form-group input,
.form-group textarea {
  padding: 12px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #018efa;
  box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.2);
  outline: none;
}

/* 喜好标签样式 */
.preferences-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.preference-tag {
  background: #ffedd5;
  color: #9a3412;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.remove-tag {
  background: none;
  border: none;
  color: #9a3412;
  cursor: pointer;
  padding: 0;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.remove-tag:hover {
  color: #7c2d12;
}

.add-preference {
  display: flex;
  align-items: center;
  gap: 5px;
}

.add-preference input {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  min-width: 120px;
}

.add-btn {
  background: #409EFF;
  color: white;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.add-btn:hover {
  background: #042fef;
}

.hint {
  font-size: 12px;
  color: #64748b;
  margin-top: 5px;
}

.save-btn {
  background: #409EFF;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;
  margin-top: 10px;
}

.save-btn:hover {
  background: #1f07f7;
  transform: translateY(-2px);
}

.save-btn i {
  font-size: 18px;
}

.security-content {
  padding: 15px 0;
}

.password-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: #fff7ed;
  border-radius: 8px;
  margin-bottom: 20px;
}

.password-info p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.password-info p i {
  color: #409EFF;
}

.change-btn {
  background: white;
  color: #409EFF;
  border: 1px solid #409EFF;
  padding: 8px 15px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.change-btn:hover {
  background: #fff7ed;
}

.password-form {
  display: grid;
  gap: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
}

.cancel-btn {
  background: white;
  color: #64748b;
  border: 1px solid #e2e8f0;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background: #f8fafc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .account-content {
    grid-template-columns: 1fr;
  }
  
  .password-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .form-actions {
    justify-content: space-between;
  }

  .account-management.student .header h1 i,
.account-management.student .save-btn {
  color: #10b981;
}

.account-management.student .save-btn {
  background: #10b981;
}

.account-management.student .save-btn:hover {
  background: #059669;
}

/* 教师特色样式 */
.account-management.teacher .header h1 i,
.account-management.teacher .save-btn {
  color: #3b82f6;
}

.account-management.teacher .save-btn {
  background: #3b82f6;
}

.account-management.teacher .save-btn:hover {
  background: #2563eb;
}

/* 根据用户类型动态添加类 */
.account-management {
  @apply student:student teacher:teacher;
}
}
</style>